const { createApp, ref } = Vue;
const { ElMessage } = ElementPlus;
const { Check, Close, Refresh, InfoFilled, User, Timer, Plus } = ElementPlusIconsVue;

const app = createApp({
    setup() {
        const deployments = ref([]);
        const managerTasks = ref([]);
        const processInstances = ref([]);
        const historyTasks = ref([]);
        const historyDialogVisible = ref(false);
        const currentTask = ref(null);
        const leaveForm = ref({
            employee: ''
        });

        // 格式化时间
        const formatDateTime = (dateStr) => {
            if (!dateStr) return '';
            const date = new Date(dateStr);
            const year = date.getFullYear();
            const month = String(date.getMonth() + 1).padStart(2, '0');
            const day = String(date.getDate()).padStart(2, '0');
            const hours = String(date.getHours()).padStart(2, '0');
            const minutes = String(date.getMinutes()).padStart(2, '0');
            const seconds = String(date.getSeconds()).padStart(2, '0');
            return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
        };

        // 获取时间线项的类型
        const getTimelineItemType = (task) => {
            if (!task.endTime) return 'warning';
            if (task.variables?.approved === true) return 'success';
            if (task.variables?.approved === false) return 'danger';
            return 'primary';
        };

        // 获取任务状态
        const getTaskStatus = (task) => {
            if (!task.endTime) return '进行中';
            if (task.variables?.approved === true) return '通过';
            if (task.variables?.approved === false) return '驳回';
            return '完成';
        };

        // 显示任务详情
        const showTaskDetail = async (task) => {
            currentTask.value = task;
            try {
                // 获取流程实例ID，根据不同来源的数据结构处理
                const processInstanceId = task.processInstanceId || task.id;
                const response = await axios.get(`/flowable/tasks/${processInstanceId}`);
                historyTasks.value = response.data.map(item => ({
                    ...item,
                    startTime: formatDateTime(item.startTime),
                    endTime: formatDateTime(item.endTime)
                }));
                historyDialogVisible.value = true;
            } catch (error) {
                ElMessage.error('获取历史任务失败：' + error.message);
            }
        };

        // 部署流程
        const deployProcess = async () => {
            try {
                const response = await axios.get('/flowable/deploy');
                ElMessage.success(response.data);
                refreshDeployments();
            } catch (error) {
                ElMessage.error('部署失败：' + error.message);
            }
        };

        // 刷新部署列表
        const refreshDeployments = async () => {
            try {
                const response = await axios.get('/flowable/deployment/list');
                deployments.value = response.data.map(item => ({
                    ...item,
                    deploymentTime: formatDateTime(item.deploymentTime)
                }));
            } catch (error) {
                ElMessage.error('获取部署列表失败：' + error.message);
            }
        };

        // 发起请假流程
        const startProcess = async () => {
            if (!leaveForm.value.employee) {
                ElMessage.warning('请输入请假人姓名');
                return;
            }
            try {
                const response = await axios.post('/flowable/start', null, {
                    params: {
                        employee: leaveForm.value.employee
                    }
                });
                ElMessage.success('请假申请提交成功');
                leaveForm.value.employee = '';
                refreshManagerTasks();
                refreshProcessInstances();
            } catch (error) {
                ElMessage.error('提交失败：' + error.message);
            }
        };

        // 刷新经理任务列表
        const refreshManagerTasks = async () => {
            try {
                const response = await axios.get('/flowable/tasks/manager');
                managerTasks.value = response.data.map(item => ({
                    ...item,
                    createTime: formatDateTime(item.createTime)
                }));
            } catch (error) {
                ElMessage.error('获取任务列表失败：' + error.message);
            }
        };

        // 审批
        const approve = async (taskId, approved) => {
            try {
                const response = await axios.post('/flowable/approve', null, {
                    params: {
                        taskId,
                        approved
                    }
                });
                ElMessage.success(response.data);
                refreshManagerTasks();
                refreshProcessInstances();
            } catch (error) {
                ElMessage.error('审批失败：' + error.message);
            }
        };

        // 刷新流程实例列表
        const refreshProcessInstances = async () => {
            try {
                const response = await axios.get('/flowable/process-instances');
                processInstances.value = response.data.map(item => ({
                    ...item,
                    startTime: formatDateTime(item.startTime),
                    endTime: formatDateTime(item.endTime)
                }));
            } catch (error) {
                ElMessage.error('获取流程实例列表失败：' + error.message);
            }
        };

        // 初始化
        refreshDeployments();
        refreshManagerTasks();
        refreshProcessInstances();

        return {
            deployments,
            managerTasks,
            processInstances,
            historyTasks,
            historyDialogVisible,
            currentTask,
            leaveForm,
            getTimelineItemType,
            getTaskStatus,
            showTaskDetail,
            deployProcess,
            startProcess,
            refreshManagerTasks,
            approve,
            refreshProcessInstances,
            refreshDeployments
        };
    }
});

app.use(ElementPlus);
// 注册图标组件
app.component('Check', Check);
app.component('Close', Close);
app.component('Refresh', Refresh);
app.component('InfoFilled', InfoFilled);
app.component('User', User);
app.component('Timer', Timer);
app.component('Plus', Plus);
app.mount('#app');